package esdclibrarypaymentsystem;

import com.esdc.paymentsystem.PaymentCoordinatorRemote;
import com.esdc.paymentsystem.exception.MemberNotExistException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author shou1dwe
 */
class Control {

    private PaymentCoordinatorRemote coordinator;
    private Input input = new Input();
    private final Long memberId;

    Control(Long memberId) {
        this.memberId = memberId;
        coordinator = Main.paymentCoordinator;
    }

    Double getOutstandingFine(Long memberId) {
        try {
            Double amount = coordinator.getOutstandingFine(memberId);
            int counter = 0;
            while (amount == null && counter < 5) {
                amount = coordinator.getOutstandingFine(memberId);
                counter++;
            }
            return amount;
        } catch (MemberNotExistException ex) {
            print(ex.getMessage());
            return null;
        }
    }

    Double payFine() {
        Double amount = null;
        while (amount == null) {
            String amountString = input.getString("amount");
            try {
                amount = Double.parseDouble(amountString);
                if(amount < 0){
                    print("Negative number: you think I am a ATM hah? ");
                    amount = null;
                    continue;
                }
            } catch (NumberFormatException ex) {
                print("Invalid number: Are you kidding me? ");
                continue;
            }
        }
        Double result = null;
        try {
            result = coordinator.payFine(memberId, amount);
        } catch (MemberNotExistException ex) {
            print(ex.getMessage());
            Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (result == null) {
            print("Payment failed");
        } else {
            print("Success");
        }
        return result;
    }

    private void print(String string) {
        System.out.println(String.format("%s", string));
    }
}
